import 'package:blocks_blkk/event/event_bus.dart';
import 'package:flutter/material.dart';

typedef SliderChangeValue = void Function(int val);
typedef RecoverPosition = bool Function();

enum SliderTypeEnum { Horizontal, Vertical }

class SliderSelf extends StatefulWidget {
  SliderSelf({
    super.key,
    required this.changeValue,
    this.backgroundColor = Colors.transparent,
    required this.controlImg,
    required this.direction,
    this.left,
    this.top,
    this.right,
    this.bottom,
    required this.width,
    required this.height,
    required this.value,
    required this.max,
    this.recoverPistion,
  });
  final SliderChangeValue changeValue;
  final Color backgroundColor;
  final String controlImg;
  final SliderTypeEnum direction; //拖动方向
  final left;
  final top;
  final right;
  final bottom;
  final width;
  final height;
  final int value;
  final int max;
  RecoverPosition? recoverPistion;

  @override
  _SliderSelfState createState() => _SliderSelfState();
}

class _SliderSelfState extends State<SliderSelf> {
  double _alightX = 0.0; //距顶部的偏移
  double _alightY = 0.0; //距左边的偏移
  double _origin = 0.0;
  int _value = 0;
  // final int max;
  // final double height;
  // final double width;
  // final SliderTypeEnum direction;
  bool toggle = false;

  _SliderSelfState() {
    // double v = ((value) * 1.0 / ((widget.max) / 2)) - 1.0;
    // if (v < -1.0) {
    //   v = -1.0;
    // } else if (v > 1.0) {
    //   v = 1.0;
    // }
    // _value = value;
    _initPosition();
  }

  void _initPosition() {
    //print('toggle $toggle');
    // if (!toggle) {
    //   if (widget.direction == SliderTypeEnum.Vertical) {
    //     _alightY =
    //         (widget.max - _value) / widget.max * (widget.height - widget.width);
    //     _alightX = 0;
    //   } else {
    //     _alightX =
    //         (widget.max - _value) / widget.max * (widget.width - widget.height);
    //     _alightY = 0;
    //   }
    // } else {
    _alightX = 0;
    _alightY = 0;
    // }
  }

  @override
  void initState() {
    super.initState();

    EventBus.instance.on('SteerReset', (arg) {
      //print('receive event SteerReset $arg toggle $toggle');
      if (!toggle) {
        _moveToCenter();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: widget.width,
      height: widget.height,
      child: GestureDetector(
        behavior: HitTestBehavior.deferToChild,
        onPanDown: (DragDownDetails details) {
          double dx = details.localPosition.dx;
          double dy = details.localPosition.dy;
          //print('onPanDown $dx,$dy');
          _moveTo(dx, dy);
        },
        onPanUpdate: (DragUpdateDetails details) {
          double dx = details.localPosition.dx;
          double dy = details.localPosition.dy;
          _moveTo(dx, dy);
        },
        onPanEnd: (DragEndDetails details) {
          //print('onPanEnd 调用');
          if (!toggle) {
            if (widget.recoverPistion != null && widget.recoverPistion!()) {
              _moveToCenter();
            }
          } else {
            _reversePosition();
          }
        },
        // onTapUp: (TapUpDetails details) {
        //   print('onTapUp 调用');
        //   _moveToCenter();
        // },
        onPanCancel: () {
          print('onPanCancel 调用');
          if (!toggle) {
            if (widget.recoverPistion != null && widget.recoverPistion!()) {
              _moveToCenter();
            }
          } else {
            _reversePosition();
          }
        },
        child: Container(
          //color: Colors.red,
          child: Stack(
            children: [
              _buildBackground(), //背景
              _buildThumb(),
            ],
          ),
        ),
      ),
    );
  }

  void _reversePosition() {
    //print('_origin = $_origin');
    if (_origin > 1) {
      _moveToMin();
    } else {
      _moveToMax();
    }
  }

  void _moveToMax() {
    setState(() {
      if (widget.direction == SliderTypeEnum.Vertical) {
        _alightY = widget.height - widget.width;
        _origin = _alightY;
      } else {
        _alightX = widget.width - widget.height;
        _origin = _alightX;
      }
    });

    widget.changeValue(0xFF);
  }

  void _moveToMin() {
    setState(() {
      if (widget.direction == SliderTypeEnum.Vertical) {
        _alightY = 0;
        _origin = _alightY;
      } else {
        _alightX = 0;
        _origin = _alightX;
      }
    });

    widget.changeValue(0);
  }

  void _moveToCenter() {
    setState(() {
      if (widget.direction == SliderTypeEnum.Vertical) {
        _alightY = (widget.height - widget.width) / 2;
        _alightX = 0;
      } else {
        _alightX = (widget.width - widget.height) / 2;
        _alightY = 0;
      }
    });

    _value = 0x80;
    widget.changeValue(_value);
  }

  void _moveTo(final double px, final double py) {
    if (widget.direction == SliderTypeEnum.Vertical) {
      _moveVertical(py);
    } else {
      _moveHorizontal(px);
    }
  }

  void _moveHorizontal(final double px) {
    double x;
    if (px >= (widget.width - widget.height / 2)) {
      x = widget.width - widget.height;
    } else if (px <= widget.height / 2) {
      x = 0;
    } else {
      x = px - widget.height / 2;
    }

    _value =
        x < 1.0 ? 1 : ((x / (widget.width - widget.height)) * 0xFE).toInt();

    widget.changeValue(_value);

    setState(() {
      _alightX = x;
    });
  }

  void _moveVertical(final double py) {
    double y;
    if (py >= (widget.height - widget.width / 2)) {
      y = widget.height - widget.width;
    } else if (py <= widget.width / 2) {
      y = 0;
    } else {
      y = py - widget.width / 2;
    }

    _value =
        y < 1.0 ? 1 : ((y / (widget.height - widget.width)) * 0xFE).toInt();
    widget.changeValue(_value);

    setState(() {
      _alightY = y;
    });
  }

  Widget _buildThumb() {
    double value = widget.width;
    if (widget.direction == SliderTypeEnum.Vertical) {
      value = widget.width;
    } else {
      value = widget.height;
    }
    return _thumb(value);
  }

  Widget _thumb(final double length) {
    return Positioned(
      left: 0,
      top: 0,
      width: length,
      height: length,
      child: Transform.translate(
        offset: Offset(_alightX, _alightY),
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(widget.controlImg),
            ),
            shape: BoxShape.circle,
          ),
        ),
      ),
    );
  }

  Positioned _buildBackground() {
    double value = widget.width / 4;
    if (widget.direction == SliderTypeEnum.Vertical) {
      value = widget.width / 4;
      return _background(value, 0, value);
    } else {
      value = widget.height / 4;
      return _background(0, value, value);
    }
  }

  Positioned _background(
      final double horizontal, final double vertical, final double radius) {
    return Positioned(
      left: horizontal,
      right: horizontal,
      top: vertical,
      bottom: vertical,
      child: Container(
        decoration: BoxDecoration(
          color: widget.backgroundColor,
          //border: Border.all(width: 2, color: Colors.orange),
          borderRadius: BorderRadius.all(Radius.circular(radius)),
        ),
      ),
    );
  }
}
